Q: Determine which class called an IntentService I am working on a news app. I have 5 categories of news sections. Each tab or section, calls to a different URL and has a separate table in the local database, hence a different URI(using a ContentProvider), when retrieving local data.
I have one AsyncTask that services all the requests. It determines which url or uri to call based on the instance of the class passed to it. All the tabs/sections/fragments/classes inherit from a common base class..
Now, I will like to change the AsyncTask to an IntentService, so I can use the AlarmManager class. I have noticed that, there seems to be no easy way of passing an object via intents.
I need a way of determining which particular class of the 5 classes called the IntentService, so the appropriate action is taken.
This class is called when the instance of the class is to be determined:
public class GetURL {
public static URL GetURL(TabsSuperClass tabs)
{
    URL url = null;
    try {
        if(tabs instanceof CultureFrag)
        {
            final String baseUri = "http://content.guardianapis.com/search?";
            Uri uriBuilder = Uri.parse(baseUri)
                    .buildUpon()
                    .appendQueryParameter("section", "culture|local|music|books|society")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("use-date", "published")
                    .appendQueryParameter("show-fields", "trailText,thumbnail")
                    .appendQueryParameter("page", String.valueOf(TabsSuperClass.pageSize))
                    .appendQueryParameter("page-size", "10")
                    .appendQueryParameter("api-key", "Test-Key")
                    .build();
            url = new URL(uriBuilder.toString());

        }
        else if(tabs instanceof LifeStyleFrag)
        {
            final String baseUri = "http://content.guardianapis.com/search?";
            Uri uriBuilder = Uri.parse(baseUri)
                    .buildUpon()
                    .appendQueryParameter("section", "lifeandstyle|education|fashion|help")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("use-date", "published")
                    .appendQueryParameter("show-fields", "trailText,thumbnail")
                    .appendQueryParameter("page", String.valueOf(LifeStyleFrag.pageSize))
                    .appendQueryParameter("page-size", "10")
                    .appendQueryParameter("api-key", "Test-Key")
                    .build();
            url = new URL(uriBuilder.toString());
        }
        else if(tabs instanceof ScienceFrag)
        {
            final String baseUri = "http://content.guardianapis.com/search?";
            Uri uriBuilder = Uri.parse(baseUri)
                    .buildUpon()
                    .appendQueryParameter("section", "science|environment|technology|business")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("use-date", "published")
                    .appendQueryParameter("show-fields", "trailText,thumbnail")
                    .appendQueryParameter("page", String.valueOf(ScienceFrag.pageSize))
                    .appendQueryParameter("page-size", "10")
                    .appendQueryParameter("api-key", "Test-Key")
                    .build();
            url = new URL(uriBuilder.toString());
        }
        else if(tabs instanceof SportFrag)
        {
            final String baseUri = "http://content.guardianapis.com/search?";
            Uri uriBuilder = Uri.parse(baseUri)
                    .buildUpon()
                    .appendQueryParameter("section", "sport|football")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("use-date", "published")
                    .appendQueryParameter("show-fields", "trailText,thumbnail")
                    .appendQueryParameter("page", String.valueOf(SportFrag.pageSize))
                    .appendQueryParameter("page-size", "10")
                    .appendQueryParameter("api-key", "Test-Key")
                    .build();
            url = new URL(uriBuilder.toString());
        }
        else if(tabs instanceof WorldFrag)
        {
            final String baseUri = "http://content.guardianapis.com/search?";
            Uri uriBuilder = Uri.parse(baseUri)
                    .buildUpon()
                    .appendQueryParameter("section", "world|opinion|media|us-news|australia-news|uk-news")
                    .appendQueryParameter("order-by", "newest")
                    .appendQueryParameter("use-date", "published")
                    .appendQueryParameter("show-fields", "trailText,thumbnail")
                    .appendQueryParameter("page", String.valueOf(WorldFrag.pageSize))
                    .appendQueryParameter("page-size", "10")
                    .appendQueryParameter("api-key", "Test-Key")
                    .build();
            url = new URL(uriBuilder.toString());
        }
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }

    return url;
}

public static Uri GetContentUri(TabsSuperClass tabs)
{
    Uri uri = null;

    if(tabs instanceof CultureFrag)
    {
        return NewsContract.CONTENT_URI_CULTURE;
    }
    else if(tabs instanceof LifeStyleFrag)
    {
        return NewsContract.CONTENT_URI_LIFESTYLE;
    }
    else if(tabs instanceof ScienceFrag)
    {
        return NewsContract.CONTENT_URI_SCIENCE;
    }
    else if(tabs instanceof SportFrag)
    {
        return NewsContract.CONTENT_URI_SPORT;
    }
    else if(tabs instanceof WorldFrag)
    {
        return NewsContract.CONTENT_URI_WORLD;
    }

    return uri;
}

}
urlConnection = (HttpURLConnection)GetURL.GetURL(_fragment).openConnection();

An instance where this class is called is here, when I am inserting data into the table of the class which called
private void InsertIntoTable(List<NewsFacade> data) {
    for (NewsFacade facade :
            data) {
        ContentValues values = new ContentValues();
        values.put(NewsContract.DataContract.COLUMN_NAME_DATE, facade.getDate());
        values.put(NewsContract.DataContract.COLUMN_NAME_CONTENT, facade.getText());
        values.put(NewsContract.DataContract.COLUMN_NAME_TAG, facade.getTag());
        byte[] image = EncodeImage(facade.getThumb());
        values.put(NewsContract.DataContract.COLUMN_NAME_THUMB, image);
        values.put(NewsContract.DataContract.COLUMN_NAME_TITLE, facade.getTitle());
        values.put(NewsContract.DataContract.COLUMN_NAME_WEBADDRESS, facade.getWebAddress());
        _fragment.mResolver.insert(GetURL.GetContentUri(_fragment), values);
    }
}

A:
I need a way of determining which particular class of the 5 classes called the IntentService, so the appropriate action is taken.

Put an extra on the Intent that you pass to startActivity() that indicates what the IntentService should do. You get a copy of that Intent in onHandleIntent() in the IntentService, so you can retrieve the extra and take appropriate steps based upon its value.

A: At the top of the activity I add:-
private final static String THIS_ACTIVITY = "AddProductToShopActivity";

for the intent I add:
intent.putExtra("CALLER", THIS_ACTIVITY);

In the started activity :-
final String caller = getIntent().getStringExtra("Caller");


Q: How can you get the version number of your Room Database? I have some code that I would only like to run when I know for certain that the Room migrations I have have completed.  Is there a way to find out which version number my Room instance is on?  I have the latest code:
@Database(entities = [AnalyticsEvent::class, ListenItem::class, LastPositionHeard::class,
DownloadItem::class], version = 3) //I would like to retrieve this information
@TypeConverters(RoomTypeConverters::class)
abstract class MyRoomDatabase : RoomDatabase() {

  abstract fun analyticsEventsDao(): AnalyticsEventsDao

  abstract fun listeningStatsDao(): ListeningStatsDao

  abstract fun lastPositionHeardDao(): LastPositionHeardDao

  abstract fun downloadsDao(): DownloadsDao

  companion object {
    // Singleton prevents multiple instances of database opening at the
    // same time.
    @Volatile
    private var INSTANCE: MyRoomDatabase? = null

    val MIGRATION_1_TO_2 = Migration1To2()
    val MIGRATION_2_TO_3 = Migration2To3()
    const val LUMINARY_DATABASE_NAME = "room_database"

    fun getDatabase(context: Context): MyRoomDatabase {
      val tempInstance = INSTANCE
      if (tempInstance != null) {
        return tempInstance
      }
      synchronized(this) {
        val instance = Room.databaseBuilder(
          context.applicationContext,
          LuminaryRoomDatabase::class.java,
          LUMINARY_DATABASE_NAME
        ).addMigrations(MIGRATION_1_TO_2, MIGRATION_2_TO_3)
        .build()
    INSTANCE = instance
    return instance
   }
  }
 }
}

But what I would like to do is something like this:
val instanceVersionNumber = MyRoomDatabase.getDatabase().versionNumber

Is it possible?

A: Here's an extension function in Kotlin to grab the version number.  The key is to call openHelper from your Room database which returns a SupportSQLiteOpenHelper object where you can then get to the actual DB attributes.
fun Context.getDBVersion() = RoomDatabase.getDatabase(this)?.openHelper?.readableDatabase?.version.toString()


Q: Twitter+OAuth Crash on iPhone OS 2.x I'm using Ben Gottlieb's Twitter+OAuth code.
Works great on my 3.1.2 iPhone, but crashes on my 2.2.1 iPhone. I'm getting a EXC_BAD_ACCESS error in the EstimateBas64EncodedDataSize call. Here's what I'm seeing in the debugger:
#0  0x2fe1e724 in __dyld_pthread_getspecific
#1  0x2fe1eddc in __dyld___gthread_getspecific
#2  0x2fe1eec8 in __dyld__Unwind_SjLj_Register
#3  0x2fe07b14 in __dyld__ZN4dyld14bindLazySymbolEPK11mach_headerPm
#4  0x2fe15ebc in __dyld_stub_binding_helper_interface
#5  0x0003cab8 in EstimateBas64EncodedDataSize at Base64Transcoder.c:106
#6  0x0003cb04 in Base64EncodeData at Base64Transcoder.c:120
#7  0x0003e476 in -[OAHMAC_SHA1SignatureProvider signClearText:withSecret:] at OAHMAC_SHA1SignatureProvider.m:50

What am I missing? A library that's not available with 2.2.1?

A: Looks like the OAuth library is being built against 3.0 frameworks. If you want to target 2.2.1, it'll need to be built against those frameworks.


Q: Displaying decoded video stream with MTKView results in undesirable blurry output I've managed to create an app that receives a live h264 encoded video stream and then decodes and displays the video with Video Toolbox and AVSampleBufferDisplayLayer. This works as expected but I want to be able to apply filters to the rendered output so I changed to decoding with Video Toolbox and displaying/rendering the decoded video with MetalKit. The only problem I have is that my rendered output with MetalKit is noticeably more blurry than the output received with AVSampleBufferDisplayLayer and I haven't managed to find out why.
Here's the output from AVSampleBufferDisplayLayer
Here's the output from MetalKit
I've tried skipping MetalKit and rendering directly to a CAMetalLayer but the same issue persists. I'm in the middle of trying to convert my CVImageBufferRef to an UIImage that I can display with UIView's. If this also ends up blurry then maybe the issue is with my VTDecompressionSession and not with the Metal side of things.
The decoding part is pretty much like what's given here How to use VideoToolbox to decompress H.264 video stream
I'll try to just paste the interesting snippets of my code.
These are the options I give my VTDecompressionSession.
NSDictionary *destinationImageBufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                                      [NSNumber numberWithInteger:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange],
                                                      (id)kCVPixelBufferPixelFormatTypeKey,
                                                      nil];

This is my view that inherits from MTKView
@interface StreamView : MTKView

@property id<MTLCommandQueue> commandQueue;
@property id<MTLBuffer> vertexBuffer;
@property id<MTLBuffer> colorConversionBuffer;
@property id<MTLRenderPipelineState> pipeline;
@property CVMetalTextureCacheRef textureCache;

@property CFMutableArrayRef imageBuffers;

-(id)initWithRect:(CGRect)rect withDelay:(int)delayInFrames;
-(void)addToRenderQueue:(CVPixelBufferRef)image renderAt:(int)frame;

@end

This is how I initialize the view from my view controller. The video I receive is of the same size, that is 666x374.
streamView = [[StreamView alloc] initWithRect:CGRectMake(0, 0, 666, 374) withDelay:0];
[self.view addSubview:streamView];

This is the content of the StreamView's initWithRect method
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
self = [super initWithFrame:rect device:device];

self.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
self.commandQueue = [self.device newCommandQueue];
[self buildTextureCache];
[self buildPipeline];
[self buildVertexBuffers];

This is the buildPipeline method
- (void)buildPipeline
{
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    id<MTLLibrary> library = [self.device newDefaultLibraryWithBundle:bundle error:NULL];

    id<MTLFunction> vertexFunc = [library newFunctionWithName:@"vertex_main"];
    id<MTLFunction> fragmentFunc = [library newFunctionWithName:@"fragment_main"];

    MTLRenderPipelineDescriptor *pipelineDescriptor = [MTLRenderPipelineDescriptor new];
    pipelineDescriptor.vertexFunction = vertexFunc;
    pipelineDescriptor.fragmentFunction = fragmentFunc;
    pipelineDescriptor.colorAttachments[0].pixelFormat = self.colorPixelFormat;

    self.pipeline = [self.device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:NULL];
}

Here is how I actually draw my texture
CVImageBufferRef image = (CVImageBufferRef)CFArrayGetValueAtIndex(_imageBuffers, 0);

id<MTLTexture> textureY = [self getTexture:image pixelFormat:MTLPixelFormatR8Unorm planeIndex:0];
id<MTLTexture> textureCbCr = [self getTexture:image pixelFormat:MTLPixelFormatRG8Unorm planeIndex:1];
if(textureY == NULL || textureCbCr == NULL)
   return;

id<CAMetalDrawable> drawable = self.currentDrawable;

id<MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer];
MTLRenderPassDescriptor *renderPass = self.currentRenderPassDescriptor;
renderPass.colorAttachments[0].clearColor = MTLClearColorMake(0.5, 1, 0.5, 1);

id<MTLRenderCommandEncoder> commandEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPass];
[commandEncoder setRenderPipelineState:self.pipeline];
[commandEncoder setVertexBuffer:self.vertexBuffer offset:0 atIndex:0];
[commandEncoder setFragmentTexture:textureY atIndex:0];
[commandEncoder setFragmentTexture:textureCbCr atIndex:1];
[commandEncoder setFragmentBuffer:_colorConversionBuffer offset:0 atIndex:0];
[commandEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4 instanceCount:1];
[commandEncoder endEncoding];

[commandBuffer presentDrawable:drawable];
[commandBuffer commit];

This is how I convert a CVPixelBufferRef into an MTLTexture
- (id<MTLTexture>)getTexture:(CVPixelBufferRef)image pixelFormat:(MTLPixelFormat)pixelFormat planeIndex:(int)planeIndex {
    id<MTLTexture> texture;
    size_t width, height;

    if (planeIndex == -1)
    {
        width = CVPixelBufferGetWidth(image);
        height = CVPixelBufferGetHeight(image);
        planeIndex = 0;
    }
    else
    {
        width = CVPixelBufferGetWidthOfPlane(image, planeIndex);
        height = CVPixelBufferGetHeightOfPlane(image, planeIndex);
        NSLog(@"texture %d, %ld, %ld", planeIndex, width, height);
    }

    CVMetalTextureRef textureRef = NULL;
    CVReturn status = CVMetalTextureCacheCreateTextureFromImage(NULL, _textureCache, image, NULL, pixelFormat, width, height, planeIndex, &textureRef);
    if(status == kCVReturnSuccess)
    {
        texture = CVMetalTextureGetTexture(textureRef);
        CFRelease(textureRef);
    }
    else
    {
        NSLog(@"CVMetalTextureCacheCreateTextureFromImage failed with return stats %d", status);
        return NULL;
    }

    return texture;
}

This is my fragment shader
fragment float4 fragment_main(Varyings in [[ stage_in ]],
                              texture2d<float, access::sample> textureY [[ texture(0) ]],
                              texture2d<float, access::sample> textureCbCr [[ texture(1) ]],
                              constant ColorConversion &colorConversion [[ buffer(0) ]])
{
    constexpr sampler s(address::clamp_to_edge, filter::linear);
    float3 ycbcr = float3(textureY.sample(s, in.texcoord).r, textureCbCr.sample(s, in.texcoord).rg);

    float3 rgb = colorConversion.matrix * (ycbcr + colorConversion.offset);

    return float4(rgb, 1.0);
}

Because the view and the video I encode are both 666x374 I tried changing the sampling type in the fragment shader to filter::nearest. I thought it would match the pixels 1:1 but it was still as blurry. Another weird thing I noticed is that if you open the uploaded images in a new tab you'll see that they are way larger than 666x374... I doubt that I'm making a mistake on the encoding side and even if I did then AVSampleBufferDisplayLayer still manages to display the video without blur so they must be doing something right that I'm missing.

A: It looks like you have the most serious issue of view scale addressed, the other issues are proper YCbCr rendering (which it sounds like you are going to avoid by outputting BGRA pixels when decoding) and then there is scaling the original movie to match the dimensions of the view. When you request BGRA pixel data the data is encoded as sRGB, so you should treat the data in the texture as sRGB. Metal will automatically do the non-linear to linear conversion for you when reading from a sRGB texture, but you have to tell Metal that it is sRGB pixel data (using MTLPixelFormatBGRA8Unorm_sRGB). To implement scaling, you just need to render from the BGRA data into the view with linear resampling. See the SO question I linked above if you want to have a look at the source code for MetalBT709Decoder which is my own project that implements proper rendering of BT.709.


Q: Is it possible to specify user specific pre commands in VS Code? We have a slew of folks doing development through the same GitLab repo. We are using VS Code tasks to execute internal commands. The main command is the same for everyone: internal_command on Windows and internalCommand on Linux.
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label" : "do it",
            "type" : "shell",
            "windows": {
                "command": "internal_command"
            },
            "linux": {
                "command": "internalCommand"
            }
        }
    ]
}

This works as expected.
Some users need/want to run a specific command before the main command. For example, one use wants to rename a file, another user wants to change an environment variable, etc...
We don't want to have multiple versions of .vscode/tasks.json cause that is a mess when pushing things to GitLab.
So I am wondering if there is a way to specify user specific tasks in the project's .vscode/tasks.json file?

A: You can with the help of the extension Command Variable it allows you to use the content of a file as a command in the terminal. The file can also contain Key-Value pairs or be a JSON file.
Say you store this userTask.txt or userTask.json file in the .vscode folder and add the file to the .gitignore file.
With the current version of the extension the file userTask.txt has to exist, I will add an option to supply alternative text in case the file does not exist. You can fill the file with a dummy command like echo No User Task
Set up your task.json like
{
  "version": "2.0.0",
  "tasks": [
    {
      "label" : "do it",
      "type" : "shell",
      "windows": {
        "command": "internal_command"
      },
      "linux": {
        "command": "internalCommand"
      },
      "dependsOrder": "sequence",
      "dependsOn": ["userTask"]
    },
    {
      "label" : "userTask",
      "type" : "shell",
      "command": "${input:getUserTask}"
    }
  ],
  "inputs": [
    {
      "id": "getUserTask",
      "type": "command",
      "command": "extension.commandvariable.file.content",
      "args": {
        "fileName": "${workspaceFolder}/.vscode/userTask.txt"
      }
    }
  ]
}


Q: How to redirect to another page after 2 clicks? I have a question about javascript. That is:
When I click first click anywhere in the website, this code will be executed

When I click secondary click anywhere in the website, I will be redirect to another page.
How to do that ?
Thank you very much ! Sorry for my poor English and programmer !

A: Put this in your page:

Sorry, I am unable to create a fiddle for this, as jsfiddle prevents iframe page redirects out of its domain.


Q: VB .NET 2008 datagridview object reference not set to an instance of an object Receiving System.NullReferenceException with my code:
Private Sub dsplay()
        ds.Clear()
        dgv_tran.DataSource = ds
        da = New OleDbDataAdapter("SELECT p.prod_id, p.prod_name, b.cost_ave " & _
                                   "FROM tbl_products p " & _
                                   "INNER JOIN tbl_balance b " & _
                                   "ON p.ID = b.p_id", con)
        da.Fill(dt)
        dgv_tran.DataSource = ds
        dgv_tran.DataMember = "table1"
call dgv_tran_CellClick(Nothing,Nothing)
end sub

Private Sub dgv_tran_CellClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgv_tran.CellClick
        Try
            Dim i As Integer = dgv_tran.CurrentRow.Index 'error starts in this line
            txtid.Text = dgv_tran.Item(0, i).Value
            txtname.Text = dgv_tran.Item(1, i).Value
            txtcost.Text = dgv_tran.Item(2, i).Value
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

My datagridview displays the data that I need, I can proceed with the project just fine when I remove the MessageBox.Show(ex.ToString) but I can't just ignore this error can I?
Already spent 4hours trying to figure this one out. Any help pointing out the problem would be much appreciated.


Q: Could the neo4j-bolt-python driver work on remote windows? I ran the Quick Example on https://github.com/neo4j/neo4j-python-driver with two environment.
 1. local linux => works well
 2. remote windows => seems like run well, however does not create graph.db.
What' wrong with me?
My Debug Log on remote windows :
2018-03-09 12:40:56,212  ~~ [CONNECT] ('192.168.1.90', 7687)
2018-03-09 12:40:56,213  ~~ [SECURE] 192.168.1.90
2018-03-09 12:40:56,221  C: [HANDSHAKE] 0x6060B017 [1, 0, 0, 0]
2018-03-09 12:40:56,224  S: [HANDSHAKE] 1
2018-03-09 12:40:56,227  C: INIT ('neo4j-python/1.5.3', {...})
2018-03-09 12:40:56,228  S: SUCCESS ({'server': 'Neo4j/3.3.2'})
2018-03-09 12:40:56,229  ~~ [CLOSE]
2018-03-09 12:40:56,231  C: RUN ('BEGIN', {})
2018-03-09 12:40:56,232  C: PULL_ALL ()
2018-03-09 12:40:56,234  C: RUN ('MERGE (a:Person {name: $name}) MERGE (a)-[:KNOWS]->(friend:Person {name: $friend_name})', {'name': 'Arthur', 'friend_name': 'Guinevere'})
2018-03-09 12:40:56,234  C: PULL_ALL ()
2018-03-09 12:40:56,237  S: SUCCESS ({'result_available_after': 0, 'fields': []})
2018-03-09 12:40:56,238  S: SUCCESS ({})
2018-03-09 12:40:56,239  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,240  S: SUCCESS ({'stats': {'labels-added': 2, 'relationships-created': 1, 'nodes-created': 2, 'properties-set': 2}, 'result_consumed_after': 0, 'type': 'w'})
2018-03-09 12:40:56,241  C: RUN ('COMMIT', {})
2018-03-09 12:40:56,241  C: PULL_ALL ()
2018-03-09 12:40:56,245  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,245  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx829'})
2018-03-09 12:40:56,246  C: RUN ('BEGIN', {'bookmark': 'neo4j:bookmark:v1:tx829', 'bookmarks': ['neo4j:bookmark:v1:tx829']})
2018-03-09 12:40:56,247  C: PULL_ALL ()
2018-03-09 12:40:56,247  C: RUN ('', {'name': 'Arthur', 'friend_name': 'Lancelot'})
2018-03-09 12:40:56,248  C: PULL_ALL ()
2018-03-09 12:40:56,250  S: SUCCESS ({'result_available_after': 0, 'fields': []})
2018-03-09 12:40:56,251  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx829'})
2018-03-09 12:40:56,251  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,252  S: SUCCESS ({'stats': {'labels-added': 1, 'relationships-created': 1, 'nodes-created': 1, 'properties-set': 1}, 'result_consumed_after': 0, 'type': 'w'})
2018-03-09 12:40:56,253  C: RUN ('COMMIT', {})
2018-03-09 12:40:56,253  C: PULL_ALL ()
2018-03-09 12:40:56,256  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,256  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx830'})
2018-03-09 12:40:56,257  C: RUN ('BEGIN', {'bookmark': 'neo4j:bookmark:v1:tx830', 'bookmarks': ['neo4j:bookmark:v1:tx830']})
2018-03-09 12:40:56,258  C: PULL_ALL ()
2018-03-09 12:40:56,259  C: RUN ('', {'name': 'Arthur', 'friend_name': 'Merlin'})
2018-03-09 12:40:56,259  C: PULL_ALL ()
2018-03-09 12:40:56,262  S: SUCCESS ({'result_available_after': 0, 'fields': []})
2018-03-09 12:40:56,263  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx830'})
2018-03-09 12:40:56,264  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,265  S: SUCCESS ({'stats': {'labels-added': 1, 'relationships-created': 1, 'nodes-created': 1, 'properties-set': 1}, 'result_consumed_after': 0, 'type': 'w'})
2018-03-09 12:40:56,265  C: RUN ('COMMIT', {})
2018-03-09 12:40:56,266  C: PULL_ALL ()
2018-03-09 12:40:56,269  S: SUCCESS ({'result_available_after': 1, 'fields': []})
2018-03-09 12:40:56,269  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx831'})
2018-03-09 12:40:56,270  C: RUN ('BEGIN', {'bookmark': 'neo4j:bookmark:v1:tx831', 'bookmarks': ['neo4j:bookmark:v1:tx831']})
2018-03-09 12:40:56,271  C: PULL_ALL ()
2018-03-09 12:40:56,271  C: RUN ('MATCH (a:Person)-[:KNOWS]->(friend) WHERE a.name = $name RETURN friend.name ORDER BY friend.name', {'name': 'Arthur'})
2018-03-09 12:40:56,273  C: PULL_ALL ()
2018-03-09 12:40:56,275  S: SUCCESS ({'result_available_after': 0, 'fields': []})
2018-03-09 12:40:56,276  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx831'})
2018-03-09 12:40:56,277  S: SUCCESS ({'result_available_after': 1, 'fields': ['friend.name']})
2018-03-09 12:40:56,277  S: RECORD * 3
2018-03-09 12:40:56,278  S: SUCCESS ({'result_consumed_after': 0, 'type': 'r'})
Guinevere
Lancelot
Merlin
2018-03-09 12:40:56,279  C: RUN ('COMMIT', {})
2018-03-09 12:40:56,279  C: PULL_ALL ()
2018-03-09 12:40:56,281  S: SUCCESS ({'result_available_after': 0, 'fields': []})
2018-03-09 12:40:56,282  S: SUCCESS ({'bookmark': 'neo4j:bookmark:v1:tx831'})

A: If I change to driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password")) from driver = GraphDatabase.driver("bolt://192.168.1.90:7687", auth=("neo4j", "password")), then it works well.  Who can explain WHY?
Debug Log changed TO
2018-03-09 12:55:47,944  ~~ [CONNECT] ('::1', 7687, 0, 0)
2018-03-09 12:55:47,945  ~~ [SECURE] ::1
2018-03-09 12:55:47,951  C: [HANDSHAKE] 0x6060B017 [1, 0, 0, 0]
2018-03-09 12:55:47,953  S: [HANDSHAKE] 1

FROM
2018-03-09 12:40:56,212  ~~ [CONNECT] ('192.168.1.90', 7687)
2018-03-09 12:40:56,213  ~~ [SECURE] 192.168.1.90
018-03-09 12:40:56,221  C: [HANDSHAKE] 0x6060B017 [1, 0, 0, 0]
2018-03-09 12:40:56,224  S: [HANDSHAKE] 1


Q: Best way to display pdf embedded in browser (chrome, IE11/Edge, Safari) I am trying to display a pdf which is created by the GET call of a RESTful service. In the HTML I am using a object tag as below
<object data={{$ctrl.miEstimatePdfData}} type="application/pdf"
    width="100%" height="100%" alt="pdf" class="view-pdf_document">

Estimate Preview Cannot be displayed.

</object>

In the js file
miEstimateService.getMitchellEstimate(response.estimate.id)
    .then(function (response) {
    var blob = new Blob([(response.data)], { type: 'application/pdf' });
    if (window.navigator.msSaveOrOpenBlob) {
        $window.navigator.msSaveOrOpenBlob(blob, "estimatePreview.pdf");
    } else {
        var fileUrl = URL.createObjectURL(blob);
        $scope.miEstimatePdfData = $sce.trustAsResourceUrl(fileUrl);
    }
});

This works flawlessly in chrome
Since IE11/ Edge does not allow displaying of the blob URL, I am using the .msSaveOrOpenBlob, but this does not open the pdf inside the browser window. It promts the user to save or open the pdf and opens it in Acrobat Reader (IE11) or in a new browser window (Edge).
In Safari, the PDF is rendered correctly in the browser but is not free flowing or scrollable, so most of the second page is not visible.
I have researched a lot and looked at a lot of the SO questions. Is there some solution which works for all the browsers - chrome, IE11/Edge and Safari?
Thanks,
SDD


Q: Xcode 7: UINavigationController's child view controller does not resize to fit parent's bounds I have a UIViewController subclass that I am pushing on to a navigation controller stack within a larger UISplitViewController. However, when I build with Xcode 7, I am finding the that the UIViewController subclass is not resizing to fit the bounds of its parent navigation controller. This was not an issue when building with previous SDKs.
When I inspect the view of the child view controller, I am getting the standard 600x600 size.
The child view controller is entirely defined in code; I am not using IB for its layout or anything like that. What gives?


Q: Variable name depending on a value I would like to create as many vecs according to a variable in a for loop. Is there an easy way?
In the example below, I would like to get 2 different Vec, the first called vec_0 and the second vec_1. Any ideas on how to do it or how can I overcome this situation in another way?
 for i in 0..2 {
        let vec_i = Vec::<i32>::with_capacity(100);
    }

A: Vecs can contain Vecs too:
let mut vecs: Vec<Vec<i32>> = vec![];  // or Vec::with_capacity(2)

for _ in 0..2 {
    vecs.push(Vec::with_capacity(100));
}


Q: fetch logs for an application in RStudio Connect? Is there a way to pulls the jobs from the logs in RStudio Connect? I know that we can go to the application, click on each job under the logs and look for info but is there a way I can pull all the logs as an API or anything? I am trying to pull the logs, tweak them and display in another app for some users.
TIA


Q: Jquery menu close after click on link I'm using http://www.hongkiat.com/blog/responsive-web-nav/ this tutorial exactly for my site menu, but the only problem is I am making a one page website. I want the mobile menu to close after I click on 'about' for example. so that it will scroll to the bottom.
I hope you can help me.
This is my cod:

k

How-to

Icons

Design

Web 2.0

Tools

                Menu

And this is the javascript:

A: The selecor is wrong
if you have
var pull        = $('#pull');

Wouldn't it be
    pull.on('click', function(e) {...

or just
$('#pull').on(...)

A: Try this. It'll execute the slideToggle function when a nav item is clicked.
menu.find('a').click(function(){
    menu.slideToggle();
});

A: If you want slideUp the Menu when you click outside of it you can use the method
stopPropagation();

http://jsfiddle.net/Joseph82/jwNEZ/


Q: How to match two tables and insert it into another table in laravel 5.4? I need to match two tables and insert it into the disbursment table, so this is my code...
    public function store(Request $request)
{
    //Approved Request
    $approvedRequest= DB::table('request')
    ->where('users_MemId',Auth::user()->MemId)
    ->where('requestStatus','Approved')
    ->join('requestdetails','request.requestId','=','requestdetails.request_requestId')
    ->join('itemattribute','requestdetails.RequestDetailsId','=','itemattribute.RequestDetailsId')
    ->join('exudeinventory', 'itemattribute.AttrName', '=', 'exudeinventory.ItemName')
    ->select('itemattribute.AttrName', 'exudeinventory.InventoryId', 'request.requestId')
    ->get();
    // dd($approvedRequest);

store function.

I've tried matching the tables and I can't figure out on how to insert the values in another table or if I am doing it right.

I've been looking for solutions but still I can't figure it out, Hope that someone would help me and explain it to me, I am new to laravel T,T

A: Maybe you can do this:
        public function store(Request $request)
        {
            //Approved Request
            $approvedRequest= DB::table('request')
            ->where('users_MemId',Auth::user()->MemId)
            ->where('requestStatus','Approved')
            ->join('requestdetails','request.requestId','=','requestdetails.request_requestId')
            ->join('itemattribute','requestdetails.RequestDetailsId','=','itemattribute.RequestDetailsId')
            ->join('exudeinventory', 'itemattribute.AttrName', '=', 'exudeinventory.ItemName')
            ->select('itemattribute.AttrName', 'exudeinventory.InventoryId', 'request.requestId')
            ->get()
            ->each (function ($request, $key) {
                $dis = new Disbursment;
                $dis->DisbursmentId = rand(1, 999999);
                $dis->ItemImage = 'default.jpg';
                $dis->ItemTypeId = $request->AttrName;
                $dis->exudeinventory_InventoryId = $request->InventoryId;
                $dis->request_requestId = $request->requestId;
                $dis->save();
            });
        }


Q: How to draw a line according to screen weight in HTML How can I draw the line showing in the picture below?

my current page looks like this:

I want to add that line at the top with the same title
(just to mention I'm using bootstrap 5)

Business

Calculator

OOG Permits

Services

Career

A: You can use flexbox. Then, you have to play with the borders. Here is an example

    <meta charset="utf-8" />
    <title>Example App</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />

FAST NAVIGATOR

Your content here

A:

fieldset {
  padding: 0;
  height: 8px;
  border-bottom: none;
}
<fieldset>
  <legend align="center">Title</legend>
</fieldset>


Q: Get index of regex match in pandas dataframe not working I have an excel worksheet that I am reading into pandas for parsing and later analysis. It has the following format. All values are strings. They will be converted to floats/ints later but having them as strings helps with parsing.
column1  |  column2 | column3 |
-----------------------------
12345   |10         |20       |
txt     |25         |65       |
35615   |15         |20       |
txt     |35         |20       |

I need to get the index of all 5 digit, numerical values in column1. It will always be a 5 digit. I am using the following regex.
\b\d{5}\b

I am having problems getting pandas to properly match the 5 digits when using any of the built in string methods.
I have tried the following.
df.column1.str.contains('\b\d{5}\b', regex=True).index.list()
df.column1.str.match('\b\d{5}\b').index.list()

I am expecting it to return
[0,2]

Both of these return an empty list. What am I doing wrong?

A: Add r before string, filter by boolean indexing and get index values to list:
i = df[df.column1.str.contains(r'\b\d{5}\b')].index.tolist()
print (i)
[0, 2]

Or if want parse only numeric values with length 5 change regex with ^ and $ for start and end of string:
i = df[df.column1.str.contains(r'^\d{5}$')].index.tolist()


Q: Get values of XML nodes with foreach I am working on a programm with C# and a XML-File. I want to read the values of the xml-nodes but I get an issue with that. In the second part, where I am trying to get the content, it only does one loop and not three. The first values are correct. I don't know why it only makes the first loop. I hope someone can help me.
My XML-File:
<?xml version="1.0" encoding="utf-8"?>
<lagerverwaltung>
  <article>
    <inventory id="1">
    </inventory>
    <orders>
      <order id="1">
        <id>1</id>
        <idposition>1</idposition>
        <content>
          <idarticle amount="4">2</idarticle>
          <idarticle amount="3">3</idarticle>
          <idarticle amount="2">1</idarticle>
        </content>
        <idcustomer>2</idcustomer>
        <orderdate>05.01.2018 15:10:44</orderdate>
        <paydate>05.02.2018</paydate>
        <mwst>7.7</mwst>
        <total>1781.358</total>
      </order>
    </orders>
  </article>
</lagerverwaltung>

My C#-Code:
List<Order> orderList = new List<Order>();
XmlDocument xml = new XmlDocument();
xml.Load(xmlFilePath);
XmlNodeList xnList = xml.SelectNodes("/lagerverwaltung/article/orders/order");
foreach (XmlNode xn in xnList)
{
    // Is working
    string id = xn["id"].InnerText;
    string bestellPositionId = xn["idposition"].InnerText;
    string kundeId = xn["idcustomer"].InnerText;
    string bestelldatum = xn["orderdate"].InnerText;
    string rechnungsDatum = xn["paydate"].InnerText;
    string mwst = xn["mwst"].InnerText;
    string rechnungsTotal = xn["total"].InnerText;

    XmlNodeList xnInhalt = xml.SelectNodes("/lagerverwaltung/article/orders/order[@id='" + id + "']/content");
    Dictionary<string, string> content= new Dictionary<string, string>();
    foreach (XmlNode xmlNode in xnInhalt) // Does only one loop
    {
        string articleid = xmlNode["idarticle"].InnerText;
        string amount = xmlNode["idarticle"].GetAttribute("amount");
        content.Add(articleid, amount);
    }
}

A: There is a single content node, use content/idarticle to get the inner collection:
XmlNodeList xnInhalt = xml.SelectNodes("/lagerverwaltung/article/orders/order[@id='" + id
+ "']/content/idarticle");

You would then modify the following code because xmlNode now refers to an idarticle. For example,
string articleid = xmlNode.InnerText;


Q: The correct way to OAuth from a desktop client without a server I am working on an extension which must connect with Facebook to download some user data. I am somewhat new to the details of the OAuth dance, and have not been able to implement this with a desired level of security. In the current setup (which works) I am concerned about evildoers hijacking my application's name and using it to post spam.
I have tried many different techniques to implement OAuth (Login With Facebook in particular) in my extension. The current setup uses Facebook's Manual Login flow.

*

*Open OAuth popup window in sandboxed tab.

*Set redirect_url to special, internal facebook page which does not require configured redirect URLs, set the auth_token parameter to return an auth_token, not temp code.

*Inject javascript into the special redirect page which posts a message to the extension with the auth_token.

This works as expected. I am able to retrieve user auth_tokens after they give my app permission via popup.
I am concerned about security since the extension does not have a server to store a secret key, nor does it have a valid domain to limit redirect_urls and verify the authenticity of authorization requests. Due to this flow: a hacker could simply download the source to my extension, steal the Facebook App ID, generate popup windows for my app from their own websites, and obtain auth_tokens which can post on behalf "via" my application.
Even more concerning, the official Google Chrome gudie to OAuth in Extensions recommends embedding your consumer_secret in the extension. This seems counter-intuitive.
I am reasonably confident this can be solved in two ways:

*

*Creating my own server which acts as a proxy between my extension and Facebook. I could set the redirect_url to my custom domain, store the consumer_secret on my server, and define a narrow API between the client and my own server.

*Restrict the authorization redirect to my Chrome Extension ID (sort of like how Facebook iOS SDK uses App store bundle identifiers). Unfortunately, I can not associate my Facebook app with a Chrome extension ID. It says "invalid URL."

I would prefer the 2nd option, as running a server can be costly and introduces another point of failure for the extension. Users also have to deal with "black box" code holding their auth_tokens, which sucks.
Interestingly, it looks like Facebook makes special exception for ms-app:// URLs (Windows 8 applications). Why not chrome-extension:// urls?
So my question: -- Is this possible? Am I missing something? Secondly: Am I being paranoid about this type of hijacking attack? It seems fairly benign, but I would rather not allow hackers to hijack my app's oauth dialog.
Thank You

A: Your intuition is correct. According to facebook's developer doc's:

Never include your App Secret in client-side or decompilable code.

The reason for this is exactly what you said, even in compiled, obfuscated byte code, it is fairly trivial using modern methods to reverse engineer the app secret, even if you are using https.
The best practice in this situation would be to have a hosted api that would be used to proxy all logins through an external source, and to hide your app id and app secret in a separate config file.


Q: Elasticsearch aggregation group by using elastic4s I want to query total sum of sales grouped by product name in Elasticsearch
How do I do that using elastic4s?
client.execute {
      search ("sales"/ "sales_type")
        .query {rangeQuery("date") gte "01-01-2018"   lte "31-12-2018" }
          .aggs { termsAgg("s1","product_name")}
             .aggs  (sumAgg("sums","total_sum"))
}

currently my code just sums up all in given date range, not grouping by product name

A: You've probably found an answer by now anyway, but here's my 2p worth for anyone else who comes across this.... you probably want to use a sub-aggregation on product_name rather than a second aggregation on the whole dataset.
Something like this (untested code, but based on a working part of one of my projects):
.query {rangeQuery("date") gte "01-01-2018"   lte "31-12-2018" }
  .aggs { termsAgg("s1","product_name").subAggregations(
             sumAgg("sums","total_sum")
          )
        }

The results come back as a bunch of nested Map[String,Any] which take a bit of sorting through, but some logging/print statements and a bit of trial and error sorted it out for me.
Reference is here: https://github.com/guardian/archivehunter/blob/47372d55d458cfe31e5d9809910cc5d9a4bbb9bf/app/controllers/SearchController.scala#L203, in that case I am processing it down for rendering in a browser frontend with ChartJS.
Apologies for brevity, but I'm on the hop at the moment and haven't got long to post :)


Q: Match NSDictionary Key Value Pairs I have the following NSDictionary with the following data structure:
Food Count (values) - Food Name (key)

I sort that NSDictionary's food count like so:
    NSArray *sortedFood = [[detailDictionary allValues] sortedArrayUsingComparator:^(id obj1, id obj2) {
    if ([obj1 intValue] < [obj2 intValue])
        return (NSComparisonResult)NSOrderedDescending;
    if ([obj1 intValue] > [obj2 intValue])
        return (NSComparisonResult)NSOrderedAscending;
    return (NSComparisonResult)NSOrderedSame;
}];

It has sorted it the following way
100
98
50
30
etc.

I am trying to use that new sortedFood array to then only show the top 5 value, key pairs for the food.
For example, if Apple's is the name of the food that has the value of 100, it would appear first.
So far I have the loop, but nothing else.
for (int i = 0; i <= 5; i++) {
}

Not sure what else to do. I think this is more difficult because the whole dictionary isn't sorted in the same way as the new array, but I could be wrong.

A: I think you should try
-[keysSortedByValueUsingSelector:] in NSDictionary, it is sorted by value and get the key results.


Q: I want to lock a part of a async method in python basically it should be a(name based lock) where name is passed as argument to the method In the below code the test() function waits for the request from UI as the request is received in  JSON form it creates a task for every request by calling handle() fucntion
async def test():
     loop = asyncio.get_running_loop()
     req = await receiver.recv_string()
     logger.debug(f"Request received {req}")
     req_json = json.loads(req)
     logger.debug("Await create_task")
     loop.create_task(handle(req_json))

async def handle(req_json_):
     req_name = req_json_.get(req_name)
    # acquire lock here based on req_name if request comes with different name acquire the lock
    # but if the request comes with same name block the request
    # untill the req for that name is completed if the request is already completed then acquire
    # the lock  with that name
     logger.info(f"Request finished with req name {req_name} for action patch stack")

How can achieve this with asyncio  module or any other way in python

A: It seems to me that all you need to do is maintain a dictionary of locks whose keys are the names given by variable req_name and whose values are the corresponding locks. If the key reg_name is not already in the dictionary, then a new lock for that key will be added:
import asyncio
from collections import defaultdict

# dictionary of locks
locks = defaultdict(asyncio.Lock)

async def handle(req_json_):
    req_name = req_json_.get(req_name)
    # acquire lock here based on req_name if request comes with different name acquire the lock
    # but if the request comes with same name block the request
    # untill the req for that name is completed if the request is already completed then acquire
    # the lock  with that name
    # Get lock from locks dictionary with name req_name. If it
    # does not exit, then create a new lock and store it with key
    # req_name and return it:
    lock = locks[req_name]
    async with lock:
        # do whatever needs to be done:
        ...
    logger.info(f"Request finished with req name {req_name} for action patch stack")

Update
If you need to timeout the attempt to acquire a lock, then create a coroutine that acquires the passed lock argument in conjunctions with a call to asyncio.wait_for with a suitable timeout argument:
import asyncio
from collections import defaultdict

async def acquire_lock(lock):
    await lock.acquire()

# dictionary of locks
locks = defaultdict(asyncio.Lock)

async def handle(req_json_):
    req_name = req_json_.get(req_name)
    lock = locks[req_name]
    # Try to acquire the lock but timeout after 1 second:
    try:
        await asyncio.wait_for(acquire_lock(lock), timeout=1.0)
    except asyncio.TimeoutError:
        # Here if the lockout could not be acquired:
        ...
    else:
        # Do whatever needs to be done
        # The lock must now be explicitly released:
        try:
            ...
            logger.info(f"Request finished with req name {req_name} for action patch stack")
        finally:
            lock.release()


Q: EmguCV detect keypoints from 3D Model Is there a way i can retrieve the observed keypoints from a 3D model instead from an image. This is since i need to track an uneven object (simple spaceship right now: http://i.msdn.microsoft.com/dynimg/IC129855.jpg) that can be visible from any side. Currently the system works somewhat fine when using an image but like i said i need it be able to identify the model if being viewed from any side. Currently using an implementation of the SURF tutorial found over here:
http://www.emgu.com/wiki/index.php/SURF_feature_detector_in_CSharp
Moreover is there a way to specify the detail of the keypoints or the number?


Q: Positioning 2 QDialog forms relative to one each other I have created 2 QDialogs forms, D1 and D2. How is it possible to make D1 and D2 have a constant distance from each other (If I move D1, D2 also moves and vise versa)?

A: I think it'll end up being a bit tedious but one thing you might try is to have both dialogs parented by a minimalist container using a window mask.  So something like...
class minimalist_container: public QWidget {
  using super = QWidget;
public:
  explicit minimalist_container (QWidget *parent = nullptr)
    : super(parent)
    {}
protected:
  virtual void resizeEvent (QResizeEvent *event) override
    {

      /*
       * Start with an empty mask.
       */
      QRegion mask;

      /*
       * Now loop though the children and add a region to
       * the mask for each child based on its geometry.
       */
      for (const auto *obj: children()) {
        if (const auto *child = dynamic_cast<const QWidget *>(obj)) {
          mask += child->geometry();
        }
      }
      setMask(mask);
      super::resizeEvent(event);
    }
};

Then you can add a layout and children to this in the usual way but the parent itself should be essentially invisible...
minimalist_container minimalist_container;
auto *minimalist_container_layout = new QHBoxLayout;
minimalist_container_layout->addWidget(new QColorDialog);
minimalist_container_layout->addStretch(1);
minimalist_container_layout->addWidget(new QFontDialog);
minimalist_container.setLayout(minimalist_container_layout);
minimalist_container.show();

The code above links all children within the masked parent widget so that they appear visually distinct but move together when the parent is moved.
There are a few niggles however.  The title bar of the parent is, by default, the only one visible whereas what I think you really want is for the parent title bar to be the only one that isn't visible.  It can certainly be hidden by setting the window flags and/or configuring your window manager but you'll probably then have to write code to handle the usual move, resize functions etc.
So, as I say... tedious, but it could certainly work.

A: You can install an event filter to monitor the moving/resizing of the source window and propagate changes to the target window. On OS X, you also need to monitor the non-client area button press, since the window move events are not sent while the window is moving, but only after it has stopped for a short time.
I leave the propagation in opposite direction as an exercise to the reader :)
// https://github.com/KubaO/stackoverflown/tree/master/questions/win-move-track-42019943
#include <QtWidgets>

class WindowOffset : public QObject {
   Q_OBJECT
   QPoint m_offset, m_ref;
   QPointer<QWidget> m_src, m_dst;
   void adjust(QEvent * event, const QPoint & delta = QPoint{}) {
      qDebug() << "ADJUST" << delta << event;
      m_dst->move(m_src->geometry().topRight() + m_offset + delta);
   }
protected:
   bool eventFilter(QObject *watched, QEvent *event) override {
#ifdef Q_OS_OSX
      if (watched == m_src.data()) {
         if (event->type() == QEvent::NonClientAreaMouseButtonPress) {
            m_ref = QCursor::pos();
            qDebug() << "ACQ" << m_ref << event;
         }
         else if (event->type() == QEvent::NonClientAreaMouseMove &&
                  static_cast<QMouseEvent*>(event)->buttons() == Qt::LeftButton) {
            auto delta = QCursor::pos() - m_ref;
            adjust(event, delta);
         }
      }
#endif
      if ((watched == m_src.data() &&
                (event->type() == QEvent::Move || event->type() == QEvent::Resize)) ||
               (watched == m_dst.data() && event->type() == QEvent::Show)) {
         if (event->type() == QEvent::Move)
            m_ref = QCursor::pos();
         adjust(event);
      }
      return false;
   }
public:
   WindowOffset(const QPoint & offset, QObject * parent = nullptr) :
      QObject{parent},
      m_offset{offset}
   {}
   WindowOffset(QWidget * src, QWidget * dst, const QPoint & offset, QObject * parent = nullptr) :
      WindowOffset{offset, parent}
   {
      src->installEventFilter(this);
      dst->installEventFilter(this);
      m_src = src;
      m_dst = dst;
   }
};

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QLabel d1{"Source"}, d2{"Target"};
   WindowOffset offset{&d1, &d2, {200, 50}};
   for (auto d : {&d1, &d2}) {
      d->setMinimumSize(300,100);
      d->show();
   }
   return app.exec();
}

#include "main.moc"


Q: Contact form 7 dropdown not working All of a sudden my drop down lists in Contact Form 7 are not working and cannot for the life of me figure it out. there are two spots where this happens as you can see in the form.
I have already looked into the code but no idea
http://www.aimbookingagency.com/offer-form/
its not listing them all and the box is SUPER tall. I am not a form expert by ANY means so I appreciate the help!

A: I did not find the problem but I re created the problem sections "SELECT dropdown menus" and it seemed to format fine. So I deleted the bad versions.
not sure if this will help anyone in the future.


Q: Code delimiter in Visual Studio I've forgot the reserved word before the # (or is it after?) for delimiter code snippets as I'd like.
You know the ones with the + for expanding the code and - for closing the code snippet. The ones the comes automatically in a class a method etc'...

A: You are looking for #region
#region foo

public static foo()
{
}

#endregion foo

However, using regions is frowned upon.

A: the name comes after the #
 #region MyClass definition
 public class MyClass
 {
 ....
 }
 #endregion

Reference: https://msdn.microsoft.com/en-us/library/9a1ybwek.aspx


Q: Read list of large .asc type files in python .memory related issue I have a folder with 50 large .asc type files each with size ~2.5Gb. These contains data from CAN signals ,how to read these files using python.I tried using numpy genfromtxt for reading files but having issues related to memory .What is the efficient way to read all the .asc files in folder into python for analysis purpose.
Thanks
Akshay

A: You would feed the data into chunks with a for loop.
Cory Schafer's video demonstrates this in his video:
https://www.youtube.com/watch?v=Uh2ebFW8OYM&t=607s


Q: Adding suffix to labels on x-axis I need to plot some values referred to time, with specific labels.
You can think of my data like the sample below:
ID     Time     Clock
260    21 hours 20:30 # this should be referred to yesterday
127    21 hours 20:30
7      5 hours  12:30
10     6 hours  11:30
8      6 hours  11:30
... ... ...
62  NaN NaN
82  NaN NaN

Time refers to time ago looking at the current one (approx UK 17:40), while Clock should be the 'watch time', i.e., the current one (approx. 17:40) minus the number of hours given by the Time column.
In Time the sorting should be from the highest to the lowest, similarly to Clock.
The column types are both objects.
In a plot, should I have the ID on the vertical axis and Clock on the x-axis.
This means on the x-axis should I have clock time, looking at Clock column. For example, 48:00 would mean 48 hours ago.
I would like to have, instead of 20:30 or 48:00, the following labels, for example: 20 hours ago, 48 hours ago.
import matplotlib.pyplot as plt

plt.scatter(df['Clock'], df['ID'])
plt.show()

However, I need some help to add a suffix (i.e., hours ago) or replace time's labels on x-axis.

A: Currently you are passing the values from the Clock column to be plotted on the x-axis and since these are strings, matplotlib interprets them as a categorical variable. If you are okay with this, then each of the x-ticks will be spaced equally apart regardless of their value (but we can sort the DataFrame before passing it), and then to get the desired tick labels you can take the portion of the string before the colon symbol (for example '20' from the string '20:30') and add the string ' hours ago' to that string to get '20 hours ago'. Then pass each of these strings as labels to the plt.xticks method, along with the original ticks in the Clock column.
import matplotlib.pyplot as plt
import pandas as pd

## recreate the data with times unsorted
df = pd.DataFrame({
    'ID':[260,127,7,10,8],
    'Time':['21 hours','21 hours','5 hours','6 hours','6 hours'],
    'Clock':['20:30','20:30','12:30','11:30','11:30',]
    })

df_sorted = df.sort_values(by='Clock',ascending=False)
plt.scatter(df_sorted['Clock'], df_sorted['ID'])

## avoid plotting duplicate clock ticks over itself
df_clock_ticks = df_sorted.drop_duplicates(subset='Clock')

## take the number of hours before the colon, and then add hours ago
plt.xticks(ticks=df_clock_ticks['Clock'], labels=df_clock_ticks['Clock'].str.split('\:').str[0] + ' hours ago')
plt.show()


Q: Using md-progress-linear inside md-dialog I am trying to use md-progress-linear inside an md-dialog. The code for my progress bar is like below.

    <md-progress-linear md-mode="determinate" value="{{testCounter}}"></md-progress-linear>

      Loading application libraries...

Normally its working fine, but when i use it inside a md-dialog its not working.
plunker link
In the above link the code i used is available, the liner bar in the home page is working fine. But when i click on open the modal is getting open, but the liner bar is not appearing.

A: Reason that your visual didn't recognized right.
Main div in dialog.html doesn't have sizes.
Put in md-dialog:
 style="width: 100px; height: 100px;"

You will see that else works correctly.


Q: Scala Spray Templated Custom Routing Directive Okay so.... I have this:
  def convertPost  = extract {
    _.request.entity.asString.parseJson.convertTo[CustomClass]
  }

  private def myRoute: Route =
    (post & terminalPath("routeness")) {
      convertPost { req =>
        detach() {
           ThingHandler.getMyResults( req )
        }
      }
    }

but I want to template it, like this:
  def convertPost[T] = extract {
    _.request.entity.asString.parseJson.convertTo[T]
  }

  private def myRoute: Route =
    (post & terminalPath("routeness")) {
      convertPost[CustomClass] { req =>
        detach() {
           ThingHandler.getMyResults( req )
        }
      }
    }

But that doesn't work.  I am using spray-json-shapeless.  My error is
Error:(28, 50) Cannot find JsonReader or JsonFormat type class for T
    _.request.entity.asString.parseJson.convertTo[T]
                                                 ^

when I try:
  def getStuff[T] = extract {
    _.request.entity.asInstanceOf[T] // .convertTo[T]
  }

it gives:
spray.http.HttpEntity$NonEmpty cannot be cast to com.stuff.CustomClass


Q: How to open my jupyter notebook on docker after starting a docker? I wanna start my container and run the jupyternotebook on it. The image is from jupyter/scipy.
First, I start my contianer. Then I try to command 'jupyter notebook' to open it but seems like the port is not 8888, it turns to 8889. I dont know how to deal with this.
enter image description here


Q: I was mocking an independent class method using the jest.spyOn but instead of mocked implementation, the actual method is called Class File
//Consumer class
class Consumer {
constructor(){
}
getConsumerData(){
//does something and does not return anything
}
}

Inside react component button click this method is being called
//ReactComponent.tsx
handleButtonClick() {
Consumer.getConsumerData();
}

Test File
  const methodSpy = jest.spyOn(Consumer.prototype, "getConsumer").mockImplementation(()=>{});
  expect(methodSpy).toHaveBeenCalled();

A: You can mock the whole Consumer

*

*Make sure Consumer is the default export of its file

import Consumer from './consumer';
///...
jest.mock('./consumer'); // SoundPlayer is now a mock constructor

beforeEach(() => {
  // Clear all instances and calls to the constructor and all methods:
  Consumer.mockClear();
});

/// Your tests

More details:
https://jestjs.io/docs/es6-class-mocks


Q: How to get WebView Content Size I am looking to find WebView content size to scale data to fit into small size of WebView Frame.
WebView is continuous loading data as getting images from IP Camera so -(void)webViewDidFinishLoad delegate method is not called, otherwise [webview sizeThatFits:CGSizeZero] would give receiver content size.
How to get WebView content size which is continuous loading data ?
Thanks,

A: See my answer to a similar question. Instead of -webViewDidFinishLoad you should consider calling this using a timer (and checking whether something has been loaded, first).
If the HTML is under your control, you might wanna call it using a JavaScipt onLoad handler that tries to fetch a custom URL that you can intercept in -webView:shouldStartLoadWithRequest:navigationType:.


Q: Calculating a windowed weighted moving average where each observation has its own weight I'm trying to calculate a windowed weighted moving average, with a window value of n. I essentially have a set of products, a price for each id, and a reference. I then calculate the ratio of the price with respect to the reference. (price = 45, reference = 45, distance = 1)
From this calculation I then obtain a weight for each observation. I would like to compare results when doing a simple moving average of all the prices and a weighted moving average.
library(tidyverse)
df <- tibble(id = c(1:15),
       price = c(40,50,34,56,78,35,23,40,50,34,56,78,35,23,12),
       product = c(sample(c("A","B"), 15, replace = TRUE)),
       reference = 45,
       distance = price / reference)

max_weight = 1
min_weight = 0

max_distance = 1
min_distance = 0

df <- df %>%
  mutate(weight = case_when(
    distance < 1 ~ (min_weight * (min_distance - distance) + max_weight * (distance - max_distance)) / (min_distance - max_distance) ,
    TRUE ~ 1
  )
  )

> df %>%
+   head()
# A tibble: 6 x 6
     id price product reference distance weight
  <int> <dbl> <chr>       <dbl>    <dbl>  <dbl>
1     1    40 B              45    0.889  0.111
2     2    50 B              45    1.11   1
3     3    34 B              45    0.756  0.244
4     4    56 A              45    1.24   1
5     5    78 B              45    1.73   1
6     6    35 A              45    0.778  0.222

Moving Average calculation:
moving_average <- function(x,n){stats::filter(x, c(0, rep(1/n,n)), sides=1) }

df <- df %>%
  group_by(product) %>%
  mutate(moving_average = moving_average(price, n =3))

> df %>%
+   head()
# A tibble: 6 x 7
# Groups:   product [2]
     id price product reference distance weight moving_average
  <int> <dbl> <chr>       <dbl>    <dbl>  <dbl>          <dbl>
1     1    40 B              45    0.889  0.111           NA
2     2    50 B              45    1.11   1               NA
3     3    34 B              45    0.756  0.244           NA
4     4    56 A              45    1.24   1               NA
5     5    78 B              45    1.73   1               41.3
6     6    35 A              45    0.778  0.222           NA

Essentially, the last step would be to calculate a moving average such that:
sum(price_i * weight_i) / sum(weight_i)
And this calculation would only take place in the given window. I can already create a column that calculates sum(price_i * weight_i), but I'm stuck when it comes to correctly adding those values n times, and then dividing them by the corresponding n weights, where n is the moving average window. Any ideas?

A: I think zoo::rollapplyr should work here. Here's a simple n=2 window,
MA <- function(X) {
  if (!is.matrix(X)) X <- matrix(X, nrow = 1)
  Hmisc::wtd.mean(X[,1], X[,2])
}
df %>%
  group_by(product) %>%
  mutate(n2 = zoo::rollapplyr(
    cbind(price, weight), 2, MA,
          by.column = FALSE, partial = TRUE)
  ) %>%
  ungroup()
# # A tibble: 15 x 7
#       id price product reference distance weight    n2
#    <int> <dbl> <chr>       <dbl>    <dbl>  <dbl> <dbl>
#  1     1    40 B              45    0.889  0.111  40
#  2     2    50 B              45    1.11   1      49
#  3     3    34 A              45    0.756  0.244  34
#  4     4    56 B              45    1.24   1      53
#  5     5    78 B              45    1.73   1      67
#  6     6    35 B              45    0.778  0.222  70.2
#  7     7    23 B              45    0.511  0.489  26.8
#  8     8    40 B              45    0.889  0.111  26.1
#  9     9    50 A              45    1.11   1      46.9
# 10    10    34 B              45    0.756  0.244  35.9
# 11    11    56 B              45    1.24   1      51.7
# 12    12    78 A              45    1.73   1      64
# 13    13    35 B              45    0.778  0.222  52.2
# 14    14    23 B              45    0.511  0.489  26.8
# 15    15    12 A              45    0.267  0.733  50.1

And here's a method demonstrating multiple windows in one call:
df %>%
  group_by(product) %>%
  mutate(
    data.frame(lapply(
      setNames(2:4, paste0("n", 2:4)),
      function(n) zoo::rollapplyr(
        cbind(price, weight), n, MA,
        by.column = FALSE, partial = TRUE)
    ))
  ) %>%
  ungroup()
# # A tibble: 15 x 9
#       id price product reference distance weight    n2    n3    n4
#    <int> <dbl> <chr>       <dbl>    <dbl>  <dbl> <dbl> <dbl> <dbl>
#  1     1    40 B              45    0.889  0.111  40    40    40
#  2     2    50 B              45    1.11   1      49    49    49
#  3     3    34 A              45    0.756  0.244  34    34    34
#  4     4    56 B              45    1.24   1      53    52.3  52.3
#  5     5    78 B              45    1.73   1      67    61.3  60.6
#  6     6    35 B              45    0.778  0.222  70.2  63.8  59.5
#  7     7    23 B              45    0.511  0.489  26.8  56.7  56.4
#  8     8    40 B              45    0.889  0.111  26.1  28.5  55.7
#  9     9    50 A              45    1.11   1      46.9  46.9  46.9
# 10    10    34 B              45    0.756  0.244  35.9  28.4  29.8
# 11    11    56 B              45    1.24   1      51.7  50.7  43.4
# 12    12    78 A              45    1.73   1      64    60.7  60.7
# 13    13    35 B              45    0.778  0.222  52.2  49.2  48.5
# 14    14    23 B              45    0.511  0.489  26.8  43.8  42.6
# 15    15    12 A              45    0.267  0.733  50.1  50.0  48.7

This method takes advantage of the not-well-known behavior of mutate with an unname argument that returns a data.frame. The use of setNames is so that the column names are meaningfully named, there are likely other ways one might approach that.
There's not a particular reason I'm using Hmisc::wtd.mean over a custom function other than I know it works well. The use of the MA function is because within zoo::rollapply*, the FUN= argument is passed a single matrix, so we need to handle it specially, even more so because due to partial=TRUE, the first time MA is called for each group, it is passed a vector instead of a matrix.


Q: Azure Devops: Approval for several Service Endpoints as a whole I´m configuring a YAML deployment pipeline for a certain app which includes several service endpoints (of different types). Deployment of this app must have an approbal from the owner of all these resources. Problem comes from the fact that you can configure an approval for each service endpoint, but not for the whole set. Due to this, the resource owner receives 5 approval requests every time the app is being deployed (and every of these has to be approbed individually).
Any way of grouping the approval of several service endpoints in only one approval step? (Looking for something like Environments, where an "Environment level" approval can be set giving acces to the whole set of resources of that Environment. Sadly, I can not put a service endpoint there, only VM´s o Kubernetes).
Remark: I think this can be achieved with classic pipelines setting a stage approval, but my requirement is using YAML.
Regards.

A: I am afraid that there is no such a feature in azure devops to group the approval requests of service endppoints currently.
Actually, the resource owner doesnot need to click multiple times to approve each individual approval request for a pipeline run.  He can simply click Approval All to approve at once
In my test yaml pipeline, I included several service endpoints in my yaml pipeline. When i run the pipeline. The resource owner will receive the approval requests. He can click the Approval All button to approve all the requests in a single click, he can also choose to approve each specific approval request. See below screenshot.

If above approval all feature in azure devops can not achieve what you expect with grouping the approval requests of service endpoints. You can suggest a feature to microsoft development team. Hope they will consider implementing this feature in the future sprint.


Q: Fetch event .focusout from input field in table cell First, I have a Google visualisation dataTable.
After that I create a for loop to get table cell values and put then in input fields:
for (var y = 0, maxrows = data.getNumberOfRows(); y < maxrows; y++) {
    for (var x = 1, maxcols = data.getNumberOfColumns(); x < maxcols; x++) {

      data.setValue(y, x, '<input id="costRedovi" vr="'+ data.getValue(y,0) + '" kol="'+ data.getColumnLabel(x) +'" class="form-control" value="'+data.getValue(y,x)+'">');
    }
}

Now every value is into table cell into input field. Now I can change those values when table is ready, but how to get those values now because  my script produce this HTML code now. Also I need to get value on event .focusout on an input field:

   <input id="costRedovi" vr="2013-04-01" kol="John Deer n7" class="form-control" value="0">
   <input id="costRedovi" vr="2013-04-01" kol="Laza Lazic" class="form-control" value="0">

I tried to do this:
new google.visualization.events.addListener(table, 'ready', function () {

    $("#costRedovi").focusout(function() {
        console.log($('#costRedovi').attr('value'));
    });

});

The problem is that every input has the same ID now.

A: If you were to use a class instead of an ID, that is:

  <input vr="2013-04-01" kol="John Deer n7" class="form-control costRedovi" value="0">
  <input vr="2013-04-01" kol="Laza Lazic" class="form-control costRedovi" value="0">

You could then retrieve the unfocused-input like so:
$(".costRedovi").focusout(function() {
  var origval = $(this).attr('value');
  var editedval = $(this).val();

  console.log("before: " + origval + ", after:" + editedval);
});


Q: Write a Python script named ten-sum-even.py which outputs the sum of only the even integers encountered My Attempt:
n = 10

total = 0

i = 0
while i < n:
    if i % 2 == 0:
    print(total)

else:
print(i)

total = total + int(input())
i = i + 1

Terminal is still counting every number

A: Mistake:
You are on right track but just printing in case its even wont help. You actually need to add that number to the total sum so far as:
n = 10
total = 0
i = 0
while i < n:
    if i % 2 == 0:
        total+=i
    else:
        print(i)
    i+=2
print(total)

Or simply:
print(sum([i for i in range(n) if i%2==0]))

A: n = 10
sum = 0

for i in range(0, n):
    if i % 2 == 0:
        sum += i
print (sum)

A: n = 10
total = 0

for i in range(10):
    if i % 2 == 0:
        total = total + i
print("Total of even numbers is " + total)


Q: Rate limiting with lua We have implemented redis based rate limiting for our web service which has been taken from here. I am duplicating the relevant code here.
local limits = cjson.decode(ARGV[1])
local now = tonumber(ARGV[2])
local weight = tonumber(ARGV[3] or '1')
local longest_duration = limits[1][1] or 0
local saved_keys = {}
-- handle cleanup and limit checks
for i, limit in ipairs(limits) do

local duration = limit[1]
longest_duration = math.max(longest_duration, duration)
local precision = limit[3] or duration
precision = math.min(precision, duration)
local blocks = math.ceil(duration / precision)
local saved = {}
table.insert(saved_keys, saved)
saved.block_id = math.floor(now / precision)
saved.trim_before = saved.block_id - blocks + 1
saved.count_key = duration .. ':' .. precision .. ':'
saved.ts_key = saved.count_key .. 'o'
for j, key in ipairs(KEYS) do

    local old_ts = redis.call('HGET', key, saved.ts_key)
    old_ts = old_ts and tonumber(old_ts) or saved.trim_before
    if old_ts > now then
        -- don't write in the past
        return 1
    end

    -- discover what needs to be cleaned up
    local decr = 0
    local dele = {}
    local trim = math.min(saved.trim_before, old_ts + blocks)
    for old_block = old_ts, trim - 1 do
        local bkey = saved.count_key .. old_block
        local bcount = redis.call('HGET', key, bkey)
        if bcount then
            decr = decr + tonumber(bcount)
            table.insert(dele, bkey)
        end
    end

    -- handle cleanup
    local cur
    if #dele > 0 then
        redis.call('HDEL', key, unpack(dele))
        cur = redis.call('HINCRBY', key, saved.count_key, -decr)
    else
        cur = redis.call('HGET', key, saved.count_key)
    end

    -- check our limits
    if tonumber(cur or '0') + weight > limit[2] then
        return 1
    end
  end
end

I am trying to figure out the meaning of the comment -- don't write in the past
I don't see how a case would be possible where old_ts is greater than now
I have put logs all over the lua code but without any success.
At maximum old_ts can be equal to saved.trim_before which in turn can be equal to now if precision is 1 and blocks is 1. But not greater .
It would be helpful if someone has insights on it.

A: If you look at the gist provided in the article
https://gist.github.com/josiahcarlson/80584b49da41549a7d5c
There is comment which asks
In over_limit_sliding_window_lua_, should

if old_ts > now then

at here be

if old_ts > saved.block_id then

And I agree to this, the old_ts is supposed to have the bucket and when the bucket jumps to the next slot, that is when old_ts will be greater then than the block_id


Q: How can I add remote repositories in Mercurial? I am working with Git repositories in the following way:

*

*I have the master repository and several remotes on the different production machines.

*I am pushing the production code to the remotes and restart the services for the changes to take effect.

I am about to switch from Git to Mercurial and I would like to know ahead how I can achieve something like that.

A: You could have a look at hg-git GitHub plugin:

adding the ability to push to and pull from a Git server repository from Mercurial.
This means you can collaborate on Git based projects from Mercurial, or use a Git server as a collaboration point for a team with developers using both Git and Mercurial.

Note: I haven't tested that tool with the latest versions of Mercurial.

A: You add entries to the [paths] section of your local clone's .hg/hgrc file.  Here's an example of a section that would go in the .hg/hgrc file:
[paths]
remote1 = http://path/to/remote1
remote2 = http://path/to/remote2

You can then use commands like hg push remote1 to send changesets to that repo.  If you want that remote repo to update is working directory you'd need to put a changegroup hook in place at that remote location that does an update.  That would look something like:
[hooks]
changegroup = hg update 2>&1 > /dev/null && path/to/script/restart-server.sh

Not everyone is a big fan of having remote repos automatically update their working directories on push, and it's certainly not the default.

A: if you want to add default path, you have to work with default in your ~project/.hg/hgrc file.  As Follows:
[paths]
default = https://path/to/your/repo

Good Luck.

A: If you're on Unix and you have Git installed, you can use this bash function to readily add a path to the remotes without a text editor:
add-hg-path() {
    git config -f $(hg root)/.hg/hgrc --add paths.$1 $2
    awk '{$1=$1}1' $(hg root)/.hg/hgrc > /tmp/hgrc.tmp
    mv /tmp/hgrc.tmp $(hg root)/.hg/hgrc
}

Then invoke it with:
$ add-hg-path remote1 https://path.to/remote1

If someone would like to build a Powershell equivalent, I'd like to include that as well. Other potentials improvements include error checking on the parameters and factoring out the call to $(hg root).


Q: How to enable HTTP Pipelining with Spray-Can I read on the spray-can docs that it supports HTTP Pipelining. But there is no method or example specified anywhere on how to do it.

A: This is a config setting. See this or this doc for all available settings in Spay config.
This setting turns it on:
spray.can.host-connector.pipelining = off

And this one has to be > 1 to effectively enable it:
spray.can.server.pipelining-limit = 1

By default pipelining is off.
Relevant description of each setting:

# The maximum number of requests that are accepted (and dispatched to
# the application) on one single connection before the first request
# has to be completed.
# Incoming requests that would cause the pipelining limit to be exceeded
# are not read from the connections socket so as to build up "back-pressure"
# to the client via TCP flow control.
# A setting of 1 disables HTTP pipelining, since only one request per
# connection can be "open" (i.e. being processed by the application) at any
# time. Set to higher values to enable HTTP pipelining.
# Set to 'disabled' for completely disabling pipelining limits
# (not recommended on public-facing servers due to risk of DoS attacks).
# This value must be > 0 and <= 128.
pipelining-limit = 1

# If this setting is enabled, the `HttpHostConnector` pipelines requests
# across connections, otherwise only one single request can be "open"
# on a particular HTTP connection.
pipelining = off


Q: Access to OctoberCMS page in code? I have a Static Page in OctoberCMS named General that has a bunch of site-wide settings including phone number and address. Is it possible to access this page in code to read these settings from its ViewBag?
UPDATE: a plugin was created with the following, where properties like twitter_username for example can now be accessed in templates with {{ general('twitter_username') }}:
use System\Classes\PluginBase;
use RainLab\Pages\Classes\Page;
use Cms\Classes\Theme;

class Plugin extends PluginBase
{
    private static $generalViewBag = null;

    public function registerMarkupTags()
    {
        return [
            'functions' => [
                'general' => function($var) {
                    if (self::$generalViewBag === null) {
                        self::$generalViewBag = Page::load(Theme::getActiveTheme(), 'general')
                            ->getViewBag();
                    }

                    return self::$generalViewBag->$var;
                },
            ],
        ];
    }
}

The twitter_username form field was added to the General page in the backend using a separate plugin:
use System\Classes\PluginBase;
use Event;

class Plugin extends PluginBase
{
    public function boot()
    {
        Event::listen('backend.form.extendFields', function($widget) {
            if (! $widget->getController() instanceof \RainLab\Pages\Controllers\Index) {
                return;
            }
            if (! $widget->model instanceof \RainLab\Pages\Classes\Page) {
                return;
            }

            switch ($widget->model->fileName) {
                case 'general.htm':
                    $widget->addFields([
                        'viewBag[twitter_username]' => [
                            'label' => 'Twitter username',
                            'type' => 'text',
                            'tab' => 'Social Media',
                        ],
                    ], 'primary');
                    break;
            }
        });
    }
}

A: yes you can do it actually you need to use this code in page life-cycle method

In page code block you can use something like this OR anywhere else

use RainLab\Pages\Classes\Page as StaticPage;

function onStart() {
    $pageName = 'static-test';
    $staticPage = StaticPage::load($this->controller->getTheme(), $pageName);
    dd($staticPage->viewBag);
}

let me know if it you find any issues


Q: Style html table when saving as csv file I have the below table

Name	Age	Country

Geronimo	26	France

Natalia	19	Spain

Silvia	32	Russia

Pet	Breed	Type

Roscoe	Pug	Dog

Polly	Parrot	Bird

Whiskers	Calico	Cat

Pet	Breed	Type

Roscoe	Pug	Dog

Polly	Parrot	Bird

Whiskers	Calico	Cat

<button>Export HTML table to CSV file</button>

and I have the below JS code
function download_csv(csv, filename) {
    var csvFile;
    var downloadLink;

    // CSV FILE
    csvFile = new Blob([csv], {type: "text/csv"});

    // Download link
    downloadLink = document.createElement("a");

    // File name
    downloadLink.download = filename;

    // We have to create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);

    // Make sure that the link is not displayed
    downloadLink.style.display = "none";

    // Add the link to your DOM
    document.body.appendChild(downloadLink);

    // Lanzamos
    downloadLink.click();
}

function export_table_to_csv(html, filename) {
    var csv = [];
    var rows = document.querySelectorAll("table tr");

    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");

        for (var j = 0; j < cols.length; j++)
            row.push(cols[j].innerText);

        csv.push(row.join(","));
    }

    // Download CSV
    download_csv(csv.join("\n"), filename);
}

document.querySelector("button").addEventListener("click", function () {
    var html = document.querySelector("table").outerHTML;
    export_table_to_csv(html, "table.csv");
});

This code converts the html tables into an csv file for download. I was wondering if it's possible to somehow add some styling to it so when the csv is open in Excel it display table header with some color to it.
Here's the fiddle Fiddle
Thanks

A: Unfortunately no! CSV files are basically raw cell data, with no formatting at all.
If you would like to have some styling you would need to learn one of the following formats. But that would be much more complicated.

*

*Office Open XML — for Excel 2007 and above

*Excel 2003 XML — for Excel 2003 and above

*Open Document Format (.ods) — can be read by Excel 2010.


Q: Fatal Error: Call to a member function write() on a non-object occurs when memory usage is very high I've been working on a web-based application to export database information through PHP. The original version of the application originally generated a single OpenXML worksheet, but ran into the issue that beyond a certain number of rows (approximately 9500), the worksheet generated was too large to import into Excel or OpenOffice.
I subsequently reworked the app to use the php_excel wrapper for libxl, which worked adequately in test, but when deployed to the live server (which had a larger amount of data in comparison to the testing server), the memory usage of the process would hit just a little bit under 2GB and then fail, giving this error:
Call to a member function write() on a non-object in...etc etc.

Now, the interesting thing is that the code works for smaller sets of data, and if I restrict the amount of data being requested, I can collect partial data dumps from the database. From all investigation, this error occurs when the code attempts to reference an object that is not assigned. Here's the code below:
$objPHPExcel = new ExcelBook($rcn, $rcl, true);
for ($i=0;$i<$myCCount;$i++){
    $myPCount = count($mySelection[$i])
    for ($j=1;$j<$myPCount;$j++){
        $myWorkSheet = $myAccountSelection[$i][0] . ' - ' . $myAccountSelection[$i][$j];
        $thisSheet = $objPHPExcel->addSheet($myWorkSheet);
        for ($k=0;$k<count($myQueryArray);$k++){
            $thisSheet->write(0, $k, $titleList[$myQueryArray[$k]]); //Error on this line
        }
    //The rest is database queries and spreadsheet generation.

Again, I'd like to reiterate that this works for smaller sets of data (same number of rows with fewer columns, or same number of columns, but fewer rows) and will run for approximately fifteen minutes before it errors out.
According to the requirements, a full data dump will generate up to a maximum of 924 workbooks (minus workbooks where there would be no actual entries), with ~360 columns in each workbook containing a combined total of 10,000+ rows.
Can anyone help me identify what the problem actually is in this case?
Edit Update:
After some logging and digging through the php_excel wrapper's error handling (such as it is), I have determined that the problem is indeed a memory allocation limit being hit - within the wrapper itself. The amount of free memory available to PHP or FastCGI or on the rest of the machine doesn't matter in this case, because once it hits a certain amount (I'm in the process of currently trying to pin down exactly what the limits are). Unless anyone can educate me as to a way to improve the amount of cells that the phpexcel wrapper can handle, I think this is closed as a "unsolvable but known problem".

A: Under some conditions, the code in this line:
$thisSheet = $objPHPExcel->addSheet($myWorkSheet);

$thisSheet will be null,
change the following code to:
if ($thisSheet) {
    for ($k=0;$k<count($myQueryArray);$k++){
        $thisSheet->write(0, $k, $titleList[$myQueryArray[$k]]); //Error on this line
    }
}

to avoid the error.
The reason why $objPHPExcel->addSheet reutuns null may be that the memory usage is reach limit, you can use ini_set("memory_limit", -1); to set memory usage to unlimited.


Q: Is there a way to make an SSRS cell display either a sub-report or an expression? I have an SSRS report that has a cell which I need to show the value of a Dataset item unless a parameter is selected, in which case I need to display a sub-report in that cell.
I tried setting the sub-report's visibility but then it never displays the expression since it takes over the entire cell. It's like it is either one way or the other.

A: If you put a subreport in a cell then you can't optionally display something else in that cell.
However from your comment you're trying to display values from two different datasets based on a condition, and you should be able to do this with an expression. Assuming there is some field in the table that can be used to relate to either dataset, then you might be able to use the lookup() function to get the relevant value, e.g. a code outline for this:
Iif(some_condition, lookup(value1 in datasetA), lookup(value1 in datasetB))


Q: How to use VBA to clear content? I would like to have all cells empty after opening my spreadsheet on "ThisWorkbook".
Code:
Sheets("1 - Feuille de Suivi").Range("C19") = ""

and
Sheets("1 - Feuille de Suivi").Liste_cible.Clear
Sheets("1 - Feuille de Suivi").Liste_cible.Value = ""

But it takes a little time before deleting, so I can see the data after opening (1-2 seconds) and it is deleted after.
Maybe you know some efficient function VBA that deletes the data while opening the spreadsheet ?
Thank you very much for your help !


Q: I am failing to run Mule 3 on the command line This is what I get on a pristine Mule distribution:
$ ./mule
MULE_HOME is set to /home/wena/src/mule-standalone-3.1.2
Running in console (foreground) mode by default, use Ctrl-C to exit...
MULE_HOME is set to /home/wena/src/mule-standalone-3.1.2
Running Mule...
--> Wrapper Started as Console
Launching a JVM...
Starting the Mule Container...
Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
  Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.

INFO  2011-07-02 05:00:33,164 [WrapperListener_start_runner] org.mule.module.launcher.MuleContainer:
**********************************************************************
* Mule ESB and Integration Platform                                  *
* Version: 3.1.2 Build: 21975                                        *
* MuleSoft, Inc.                                                     *
* For more information go to http://www.mulesoft.org                 *
*                                                                    *
* Server started: 2011/07/02 5:00 AM                                 *
* JDK: 1.6.0_18 (mixed mode)                                         *
* OS: Linux (2.6.39-2-686-pae, i386)                                 *
* Host: debian (127.0.1.1)                                           *
**********************************************************************
INFO  2011-07-02 05:00:33,247 [WrapperListener_start_runner] org.mule.module.launcher.application.DefaultMuleApplication:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ New app 'default'                                        +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ERROR 2011-07-02 05:00:33,250 [WrapperListener_start_runner] org.mule.module.launcher.DeploymentService:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Failed to deploy app 'default', see below                +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ERROR 2011-07-02 05:00:33,250 [WrapperListener_start_runner] org.mule.module.launcher.DeploymentService: org.mule.module.launcher.DeploymentException: Failed to deploy application [default]
INFO  2011-07-02 05:00:33,254 [WrapperListener_start_runner] org.mule.module.launcher.StartupSummaryDeploymentListener:

**********************************************************************
*            - - + APPLICATION + - -            * - - + STATUS + - - *
**********************************************************************
* default                                       * FAILED             *
**********************************************************************

INFO  2011-07-02 05:00:33,279 [WrapperListener_start_runner] org.mule.module.launcher.DeploymentService:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Mule is up and kicking (every 5000ms)                    +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

I am however able to run Mule from Eclipse.
Note that a recent development snapshot leading to 3.2 release didn't have any such problem.

A: Mule is failing probably because an empty directory (lib/shared/default) is missing.
Hg doesn't version empty directories.

A: There is something weird that Mercurial (Debian's 1.8.3-1+b1 in Unstable) does: whenever I run hg clean, even if there is nothing to clean (hg status output is null), trying to run ./mule fails with the stated error.
Solution: stay away from that clean command for now.


Q: Django: Put multiple widgets/fields into one field I'm making a form to let users edit their photo gallery. So when I show the form I need 2 fields/widget per photo.
For each photo there will be one
CheckBox(label='Delete photo', value=<Id of photo>)
and one RadioSelect(label='Set as cover image', value=<Id of photo>)
In the form class I guess I should put something like this in the __init__:
for image in images:
    #make a checkbox widget
    #make a radio select
    #store the url of the image
    self.fields[..] = gallery_field_widget

I would prefer to put as much code in the form class instead of the template. I've played around with MultpleSelect widget but I can't figure out how to iterate through it together with the rest of the widgets.. and help on this?

A: This isn't two widgets per field, this is two fields per form and one form per instance. For that we have formsets.


Q: Mapping 2 columns in pandas to third one I want to create pandas column 'Link' based on other 2 columns (URL and Title) in order to create column which will hold HTML link tag with title in form:
{}'.format(df['Ad_URL'],df['Title'])
I'm using:
def Ad_Link(df):
    return ('{}'.format(df['Ad_URL'],df['Title']))

df['Link'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link(x), axis=1)

but it doesn't work as expected.
It gives:
List of all Titles for all items in  df['Link']
It suppose iterate and give:
Title[0]
Title[1]

EDIT
Actually my solution worked, had a problem with data frame initially.

A: This works fine for me.
df = pd.DataFrame({'Ad_URL':['u1', 'u2', 'u3'], 'Title':['t1', 't2', 't3']})

def Ad_Link(df):
    return ('{}'.format(df['Ad_URL'],df['Title']))

df['Link'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link(x), axis=1)

print(df)

Output:
  Ad_URL Title                 Link
0     u1    t1  t1
1     u2    t2  t2
2     u3    t3  t3

A: First your code working for me nice. But added multiple solutions with same output:
df = pd.DataFrame({'Ad_URL':['u1', 'u2', 'u3'], 'Title':['t1', 't2', 't3']})

def Ad_Link(df):
    return ('{}'.format(df['Ad_URL'],df['Title']))

df['Link'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link(x), axis=1)

#change variable in function to x
def Ad_Link1(x):
    return ('{}'.format(x['Ad_URL'],x['Title']))

df['Link1'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link1(x), axis=1)

#removed lambda function
def Ad_Link2(x):
    return ('{}'.format(x['Ad_URL'],x['Title']))

df['Link2'] = df.apply(Ad_Link2, axis=1)

#pass columns names to lambda function, changed function
def Ad_Link3(url, link):
    return ('{}'.format(url, link))

df['Link3'] = df.apply(lambda x: Ad_Link3(x['Ad_URL'],x['Title']), axis=1)

#only lambda function solution
df['Link4'] = df.apply(lambda x: '{}'.format(x['Ad_URL'], x['Title']), axis=1)

print (df)
  Ad_URL Title                 Link                Link1                Link2  \
0     u1    t1  t1  t1  t1
1     u2    t2  t2  t2  t2
2     u3    t3  t3  t3  t3

                 Link3                Link4
0  t1  t1
1  t2  t2
2  t3  t3


Q: How to integrate key vault with Bot composer I want to make an http request from bot composer but one thing to pass while making http request needs to be kept a secret. So I want to fetch that value from key vault. Can someone tell how to integrate bot composer with key vault.

A: I'll assume you are using Azure to run the bot, so I'll answer with that in mind. Otherwise let me know and I can expand the answer.
Take the secret from the settings of the bot. It's just like how you access turn.activity.text, but using settings scope instead of the turn scope. So: settings.apiSecret.
Local Env
Now in development, local environment, you can just put the secret in the settings file.
In Azure
When you deploy to your azure app service, you can use Key Vault References in the Configuration blade. Remember you need to give the app service Secret Get permission to that Key Vault.
This is the easiest way since you don't need to write code to query KeyVault via the API.
From DevOps to Azure
There's a way to get the secret in the pipeline, but I believe this is not something you need in this scenario, you just want to set the variable in the App Service. So in the App Service Deployment task, under Application and Configuration settings -> App Settings: you can add the same thing you'd put in the Configuration blade in the azure portal.
So you can add to the textbox: -apiSecret @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/) or click on the button with the elipsis on the right and enter it on the form


Q: Javascript multiple countdown timers on the same page using dates from django models this is my first ever post so please let me know if I need to clarify anything thanks.
I don't have any Javascript experience and I'm trying to write a countdown timer that runs through a django model's data and displays a countdown timer based on each individual object date in my database.
My django models work correctly and loops correctly etc.
I place the below script within my django models for loop but the script only pulls the first objects target date and then populates the countdown timer(correctly) for my first django model object's targetdate but it uses the date of only this first model.
My guess is that I need to put the targetdate (the folowing piece of code) :
let targetdate  = new Date({{ datemodel.dateinmodel|date:"U" }} * 1000);

also in some sort of for loop within javascript itself. I've tried to do this but I really still struggle a lot with javascript at the moment so I don't have any idea.
Do I need to put the target date also in some sort of loop within my javascript script to be able to make it loop through the rest of the object dates in my django model?
Please find the script that I've got so far below :

    Countdown until target date-
    D
    H
    M
    S

Any guidance on how I should approach this will be appreciated many thanks.

A: This is not an answer though but I'm facing similar challenge.. I don't know if you've sorted it out.   I tried converting the data to JSON using JSON dump with that the whole params comes out for each of the timers. And I see that in my console.log so next challenge is to be able to pass all to the table through a loop I was thinking although it's not conventional but might work. Creating another table close to the main table to move this timer out of the for loop entirely and work from there with it..
This is the link to a solution that worked for me https://stackoverflow.com/a/65218112/16174649

A: Thanks for the suggestion.
I was unable to get it to work within the Django loop itself so my solution was to seperate and load each date object seperately within the views file in django and then to just build a counter for each date by itself.
Its probably not the most effective solution but it worked as I only had 11 plus dates to build countdowns for.
In the code example below I would simply update/+1 number for the "countDownDate", "date" and "demo" fields until I created 11 scripts for my 11 items so each item/section has its own countdown script.
Below is the first and second script as an example.


Q: parsing error while parsing document using ow3c.dom.Document object, (Unicode: 0x1a) was found in the element content of the document I am getting error : org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 14515; An invalid XML character (Unicode: 0x1a) was found in the element content of the document.
my xml file content in which I getting error:
 <Product>
          <Description>672577000 3M 4540 DISPOSABLE COVERALL → XL</Description>
 </Product>

I got this error while I am parsing document using org.w3c.dom.Document object, error is occurred due to → in input file. so how can I fix this issue ?

A: No all characters are allowed in a xml files. Here is a link for you to find which one is allowed or is discouraged and the reset is not allowed:
http://en.wikipedia.org/wiki/Valid_characters_in_XML
Yours (→) is not allowed.

A: I resolved this by using below code
String removedUnicodeChar  = "DISPOSABLE COVERALL → XXL</Description></Order> ↔ ↕ ↑ ↓ → ABC";
Pattern pattern = Pattern.compile("[\\p{Cntrl}|\\uFFFD]");
Matcher m = pattern.matcher(removedUnicodeChar);
if(m.find()){
    System.out.println("Control Characters found");
    removedUnicodeChar = m.replaceAll("");
}